package team1.hdhnewsapp.weatheractivity;

import info.androidhive.slidingmenu.R;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import team1.hdhnewsapp.weather.model.Weather;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;

public class EnglandWeatherFragment extends Fragment {
	ListView lv;
	Weather thoitiet = new Weather();
	List<Weather> weather = new ArrayList<Weather>();
	MyArrayAdapter adapter;
	ProgressBar pro;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_engweather,
				container, false);
		String[] city1 = { "Birmingham,England", "Bristol,England",
				"Cambridge,England", "Canterbury,England", "Carlisle,England" };
		lv = (ListView) rootView.findViewById(R.id.list1);
		pro = (ProgressBar) rootView.findViewById(R.id.probar3);
		pro.setVisibility(View.VISIBLE);

		JSONWeatherTask task = new JSONWeatherTask();
		task.execute(city1);
		weather.clear();
		return rootView;
	}

	private class JSONWeatherTask extends
			AsyncTask<String, Integer, List<Weather>> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pro.setVisibility(View.VISIBLE);
		}

		@Override
		protected List<Weather> doInBackground(String... params) {
			for (int i = 0; i < params.length; i++) {
				String data = ((new WeatherHttpClient())
						.getWeatherData(params[i]));
				try {
					thoitiet = JSONWeatherParser.getWeather(data);
					thoitiet.iconData = ((new WeatherHttpClient())
							.getImage(thoitiet.currentCondition.getIcon()));
					weather.add(thoitiet);
					publishProgress(i);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return weather;

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(List<Weather> weather) {
			super.onPostExecute(weather);
			adapter = new MyArrayAdapter(getActivity(), R.layout.list_item,
					weather);
			lv.setAdapter(adapter);
			pro.setVisibility(View.INVISIBLE);
		}

	}
}
